package com.ssh.demo.config;

import com.ssh.demo.core.NettyServer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName NettyStarter
 * @Description TODO
 * @Author ssh
 * @Date 2021/4/12 11:20
 */
@Slf4j
@Configuration
@ComponentScan(basePackages = {
        "com.ssh.demo"
})
@AllArgsConstructor
public class NettyStarter implements ApplicationListener<ApplicationStartedEvent> {

    private NettyConfig nettyConfig;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        //是否启动Netty服务
        if (!nettyConfig.getEnabled()) {
            log.info("Netty server is disabled !");
            return;
        }
        //创建TcpNetty实例
        NettyServer tcpServer = (NettyServer) applicationStartedEvent.getApplicationContext().getBean("tcp-netty");
        //启动TCP服务
        if (tcpServer.start()) {
            log.info("tcp server started on port {}", nettyConfig.getTcpPort());
        } else {
            log.error("tcp server start failed!");
        }
        //创建UdpNetty实例
        NettyServer udpServer = (NettyServer) applicationStartedEvent.getApplicationContext().getBean("udp-netty");
        //启动udp服务
        if (udpServer.start()) {
            log.info("udp server started on port {}", nettyConfig.getUdpPort());
        } else {
            log.error("udp server start failed!");
        }


    }
}
